Skip to content

Import Aliases

One of the downsides to file-based routing is that we tend to wind up with sprawling directory structures. It's not uncommon to see stuff like this:

// /src/app/profiles/[:profileId]/page.js
import React from 'react';
import { getProfileInfo } from '../../../helpers';
async function ProfilePage({ params }) {
// Stuff here
}
export default ProfilePage;

As you might've already discovered, having to count the number of ../ gets pretty annoying 😬. It also makes it hard to restructure things and move files around.

Fortunately, there's a solution: import aliases.

This comes built into Next, when you use create-next-app. It looks like this:

import { getProfileInfo } from '@/helpers';

@ is an alias for our root directory, src. This makes the import paths absolute instead of relative; we can move this file anywhere in the codebase, and the import will still resolve correctly.

We can also customize the symbol we want to use as the import alias. That's what this question is about, during the initial project creation flow:

? Would you like to customize the default import alias? › No / Yes

If you select “Yes”, you'll be prompted to select a new character. In practice, most devs stick with the default. The only other semi-popular option I've seen is the dollar sign ($). I've also heard from some folks who use the tilde (~).

Downsides?

Import aliases offer a pretty big quality-of-life improvement, especially when working with Next. That said, that benefit isn't free. There's one significant trade-off that may be worth considering.

Import aliases aren't actually a thing in JavaScript. This is custom syntax, implemented at the bundler level; tools like Webpack will essentially do a find-and-replace for us during the build, filling in the real paths.

This can cause problems if we have other tools that need to work with these files. For example, if you have a unit testing library and you try to import some of these files, that tool will throw an exception, since it won't know how to resolve the file path.

A few years ago, this was a really common issue. Fortunately, nowadays, most tools support import aliases. Usually, it's a quick matter of checking the docs for the project in question, and figuring out how to configure it to use the same alias as the Next app.

And so, I think import aliases are safe to use for most developers, but if you happen to use niche or obscure JS tooling, it may be worth checking for compatibilty first.